package com.lancoo.evaluate.api;

import android.Manifest;
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.lancoo.evaluate.bean.Evaluate;
import com.lancoo.evaluate.bean.EvaluateResult;
import com.lancoo.evaluate.util.ResultParse;
import com.lancoo.evaluate.util.Util;
import com.lancoo.evaluate.util.permission.PermissionsManager;
import com.lancoo.evaluate.util.permission.PermissionsResultAction;
import com.tt.SkEgnManager2;
import com.tt.lancoo.OnEvaluateCallback;
import com.tt.lancoo.OnRecordCallback;
import com.tt.listener.OnInitEngineListener;
import com.tt.setting.EngineSetting;

import java.io.File;
import java.util.ArrayList;

public class EvaluateContext {
    private static final String TAG = EvaluateContext.class.getName();
    // Parameter
    private Activity mActivity;
    private String mUserId;
    // callback
    private OnContextInitCallback mOnContextInitCallback;
    private OnEvaluatedCallback mOnEvaluatedCallback;
    // Data And Logic
    private ArrayList<Evaluate> mEvaluates;
    private ArrayList<EvaluateResult> mEvaluateResults;
    private int mIndex;

    public EvaluateContext(Activity activity, String userId) {
        mActivity = activity;
        mUserId = userId;
    }

    public void setOnContextInitCallback(OnContextInitCallback callback) {
        mOnContextInitCallback = callback;
        requestAllPermissions();
    }

    public void setOnEvaluatedCallback(OnEvaluatedCallback callback) {
        mOnEvaluatedCallback = callback;
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    private void requestAllPermissions() {
        String[] permissions = new String[]{
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(
                mActivity,
                permissions,
                new PermissionsResultAction() {
                    @Override
                    public void onGranted() {
                        initEngine();
                    }

                    @Override
                    public void onDenied(String permission) {
                        Toast.makeText(mActivity.getApplicationContext(), "请允许所有权限", Toast.LENGTH_SHORT).show();
                        Util.openAppSetting(mActivity);
                    }
                }
        );
    }

    private void initEngine() {
        final EngineSetting setting = EngineSetting.getInstance(mActivity);
        setting.setOnInitEngineListener(new OnInitEngineListener() {
            @Override
            public void onStartInitEngine() {
                Log.e(TAG, "-------------------->" + "开始初始化引擎");
            }

            @Override
            public void onInitEngineSuccess() {
                Log.e(TAG, "-------------------->" + "初始化引擎成功");
                if (mOnContextInitCallback != null) mOnContextInitCallback.onContextInit();
            }

            @Override
            public void onInitEngineFailed() {
                Toast.makeText(mActivity.getApplicationContext(), "初始化引擎失败", Toast.LENGTH_SHORT).show();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                SkEgnManager2.getInstance(mActivity).initCloudEngine(
                        "148757611600000f",
                        "2d5356fe1d5f3f13eba43ca48c176647",
                        mUserId,
                        setting
                );
            }
        }).start();
    }

    public void startRecord(File wav, OnRecordCallback callback) {
        SkEgnManager2.getInstance(mActivity).startRecord2(wav, callback);
    }

    public boolean isRecording() {
        return SkEgnManager2.getInstance(mActivity).isRecording();
    }

    public void stopRecord() {
        SkEgnManager2.getInstance(mActivity).stopRecord2();
    }

    @Deprecated
    public void startEvaluate(ArrayList<Evaluate> evaluates, OnEvaluatedCallback callback) {
        mOnEvaluatedCallback = callback;
        startEvaluate(evaluates);
    }

    public void startEvaluate(ArrayList<Evaluate> evaluates) {
        if (evaluates.isEmpty()) throw new IllegalArgumentException("evaluate list is empty");
        if (mEvaluates == null) mEvaluates = new ArrayList<>();
        if (mEvaluateResults == null) mEvaluateResults = new ArrayList<>();
        mEvaluates.addAll(evaluates);
        mIndex = 0;
        startEvaluate();
    }

    private void startEvaluate() {
        Evaluate evaluate = mEvaluates.get(mIndex);

        String pcmPath = evaluate.getPcmPath();
        if (TextUtils.isEmpty(pcmPath)) {
            handleNoPcm(evaluate);
            return;
        }
        File pcm = new File(pcmPath);
        if (!pcm.exists() || pcm.length() == 0) {
            handleNoPcm(evaluate);
            return;
        }

        int qType = evaluate.getQType();
        String coreType = evaluate.getCoreType();
        String refText = evaluate.getRefText();
        String keywords = evaluate.getKeywords();

        OnEvaluateCallback callback = new OnEvaluateCallback() {
            @Override
            public void onEvaluateEnd(String result) {
                Evaluate evaluate = mEvaluates.get(mIndex);
                EvaluateResult evaluateResult = ResultParse.parse(evaluate, result);
                mEvaluateResults.add(evaluateResult);
                if (mEvaluateResults.size() == mEvaluates.size()) {
                    mOnEvaluatedCallback.onEvaluated(mEvaluateResults);
                    mEvaluateResults.clear();
                    mEvaluates.clear();
                } else {
                    mIndex++;
                    startEvaluate();
                }
            }
        };

        if (TextUtils.isEmpty(keywords)) {
            SkEgnManager2.getInstance(mActivity).startEvaluate(
                    pcm,
                    coreType,
                    refText,
                    qType,
                    callback
            );
        } else {
            SkEgnManager2.getInstance(mActivity).startEvaluate(
                    pcm,
                    coreType,
                    refText,
                    qType,
                    keywords,
                    callback
            );
        }
    }

    private void handleNoPcm(Evaluate evaluate) {
        EvaluateResult evaluateResult = new EvaluateResult();
        evaluateResult.setError("the evaluate object " + evaluate + " has no pcm");
        mEvaluateResults.add(evaluateResult);
        if (mEvaluateResults.size() == mEvaluates.size()) {
            mOnEvaluatedCallback.onEvaluated(mEvaluateResults);
            mEvaluateResults.clear();
            mEvaluates.clear();
        } else {
            mIndex++;
            startEvaluate();
        }
    }

    public void onDestroy() {
        SkEgnManager2.getInstance(mActivity).recycle();
    }
}
